# -*- coding: utf-8 -*-
"""
分析结果解析模块
负责解析LLM返回的分析结果
"""

import re
import json
from typing import Dict, Any, List, Optional
from common.logger import get_logger

logger = get_logger(__name__)


class ResultParser:
    """分析结果解析器"""
    
    def __init__(self):
        """初始化结果解析器"""
        # 定义解析模式
        self.parsing_patterns = {
            'severity': [
                r'严重程度[：:]\s*(.+)',
                r'级别[：:]\s*(.+)',
                r'严重性[：:]\s*(.+)',
                r'危险程度[：:]\s*(.+)'
            ],
            'problem': [
                r'问题[：:]\s*(.+)',
                r'异常[：:]\s*(.+)',
                r'错误[：:]\s*(.+)',
                r'故障[：:]\s*(.+)'
            ],
            'cause': [
                r'原因[：:]\s*(.+)',
                r'错误原因[：:]\s*(.+)',
                r'故障原因[：:]\s*(.+)',
                r'导致[：:]\s*(.+)'
            ],
            'solution': [
                r'解决方案[：:]\s*(.+)',
                r'建议[：:]\s*(.+)',
                r'解决方法[：:]\s*(.+)',
                r'修复[：:]\s*(.+)'
            ],
            'attention': [
                r'需要关注[：:]\s*(.+)',
                r'立即处理[：:]\s*(.+)',
                r'紧急[：:]\s*(.+)',
                r'重要[：:]\s*(.+)'
            ]
        }
        
        # 编译正则表达式
        self.compiled_patterns = {}
        for category, patterns in self.parsing_patterns.items():
            self.compiled_patterns[category] = [re.compile(pattern, re.IGNORECASE) for pattern in patterns]
    
    def parse_analysis_result(self, analysis_text: str) -> Dict[str, Any]:
        """
        解析分析结果文本
        
        Args:
            analysis_text: LLM返回的分析结果文本
            
        Returns:
            解析后的结构化结果
        """
        if not analysis_text:
            return {}
        
        try:
            parsed_result = {
                'original_text': analysis_text,
                'severity': self._extract_severity(analysis_text),
                'problem': self._extract_problem(analysis_text),
                'cause': self._extract_cause(analysis_text),
                'solution': self._extract_solution(analysis_text),
                'attention_required': self._extract_attention(analysis_text),
                'keywords': self._extract_keywords(analysis_text),
                'confidence': self._calculate_confidence(analysis_text)
            }
            
            return parsed_result
            
        except Exception as e:
            logger.error(f"解析分析结果失败: {e}")
            return {'original_text': analysis_text, 'parse_error': str(e)}
    
    def parse_analysis_results(self, results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        批量解析分析结果
        
        Args:
            results: 分析结果列表
            
        Returns:
            解析后的结果列表
        """
        parsed_results = []
        
        for result in results:
            try:
                analysis_text = result.get('analysis_result', '')
                parsed_data = self.parse_analysis_result(analysis_text)
                
                # 合并原始结果和解析结果
                parsed_result = {**result, 'parsed_data': parsed_data}
                parsed_results.append(parsed_result)
                
            except Exception as e:
                logger.error(f"解析单条分析结果失败: {e}")
                parsed_results.append({
                    **result,
                    'parsed_data': {'original_text': result.get('analysis_result', ''), 'parse_error': str(e)}
                })
        
        return parsed_results
    
    def _extract_severity(self, text: str) -> Optional[str]:
        """
        提取严重程度
        
        Args:
            text: 分析文本
            
        Returns:
            严重程度
        """
        for pattern in self.compiled_patterns['severity']:
            match = pattern.search(text)
            if match:
                return match.group(1).strip()
        return None
    
    def _extract_problem(self, text: str) -> Optional[str]:
        """
        提取问题描述
        
        Args:
            text: 分析文本
            
        Returns:
            问题描述
        """
        for pattern in self.compiled_patterns['problem']:
            match = pattern.search(text)
            if match:
                return match.group(1).strip()
        return None
    
    def _extract_cause(self, text: str) -> Optional[str]:
        """
        提取原因分析
        
        Args:
            text: 分析文本
            
        Returns:
            原因分析
        """
        for pattern in self.compiled_patterns['cause']:
            match = pattern.search(text)
            if match:
                return match.group(1).strip()
        return None
    
    def _extract_solution(self, text: str) -> Optional[str]:
        """
        提取解决方案
        
        Args:
            text: 分析文本
            
        Returns:
            解决方案
        """
        for pattern in self.compiled_patterns['solution']:
            match = pattern.search(text)
            if match:
                return match.group(1).strip()
        return None
    
    def _extract_attention(self, text: str) -> bool:
        """
        提取是否需要关注
        
        Args:
            text: 分析文本
            
        Returns:
            是否需要关注
        """
        attention_keywords = ['需要立即关注', '紧急', '重要', '立即处理', '需要关注']
        text_lower = text.lower()
        
        for keyword in attention_keywords:
            if keyword.lower() in text_lower:
                return True
        
        # 检查模式匹配
        for pattern in self.compiled_patterns['attention']:
            match = pattern.search(text)
            if match:
                attention_text = match.group(1).strip().lower()
                if any(keyword in attention_text for keyword in ['是', '需要', '紧急', '重要']):
                    return True
        
        return False
    
    def _extract_keywords(self, text: str) -> List[str]:
        """
        提取关键词
        
        Args:
            text: 分析文本
            
        Returns:
            关键词列表
        """
        # 定义关键词模式
        keyword_patterns = [
            r'错误|error|exception|异常',
            r'警告|warning|warn',
            r'失败|fail|failure',
            r'超时|timeout',
            r'连接|connection|connect',
            r'数据库|database|db',
            r'网络|network',
            r'内存|memory',
            r'CPU|cpu',
            r'磁盘|disk',
            r'权限|permission|auth',
            r'配置|config|configuration'
        ]
        
        keywords = []
        for pattern in keyword_patterns:
            matches = re.findall(pattern, text, re.IGNORECASE)
            keywords.extend(matches)
        
        # 去重并返回
        return list(set(keywords))
    
    def _calculate_confidence(self, text: str) -> float:
        """
        计算解析置信度
        
        Args:
            text: 分析文本
            
        Returns:
            置信度分数 (0-1)
        """
        confidence = 0.0
        
        # 检查是否包含关键信息
        if self._extract_severity(text):
            confidence += 0.2
        if self._extract_problem(text):
            confidence += 0.3
        if self._extract_cause(text):
            confidence += 0.2
        if self._extract_solution(text):
            confidence += 0.2
        if self._extract_keywords(text):
            confidence += 0.1
        
        return min(confidence, 1.0)
    
    def classify_severity(self, severity_text: str) -> str:
        """
        分类严重程度
        
        Args:
            severity_text: 严重程度文本
            
        Returns:
            标准化的严重程度
        """
        if not severity_text:
            return 'UNKNOWN'
        
        severity_lower = severity_text.lower()
        
        if any(keyword in severity_lower for keyword in ['严重', '致命', 'critical', 'fatal']):
            return 'CRITICAL'
        elif any(keyword in severity_lower for keyword in ['错误', 'error', '异常', 'exception']):
            return 'ERROR'
        elif any(keyword in severity_lower for keyword in ['警告', 'warning', 'warn']):
            return 'WARNING'
        elif any(keyword in severity_lower for keyword in ['信息', 'info', 'information']):
            return 'INFO'
        elif any(keyword in severity_lower for keyword in ['调试', 'debug']):
            return 'DEBUG'
        else:
            return 'UNKNOWN'
    
    def extract_structured_data(self, text: str) -> Dict[str, Any]:
        """
        提取结构化数据
        
        Args:
            text: 分析文本
            
        Returns:
            结构化数据
        """
        structured_data = {
            'severity_level': 'UNKNOWN',
            'problem_type': 'UNKNOWN',
            'affected_components': [],
            'error_codes': [],
            'timestamps': [],
            'ip_addresses': [],
            'urls': []
        }
        
        # 提取严重程度
        severity = self._extract_severity(text)
        if severity:
            structured_data['severity_level'] = self.classify_severity(severity)
        
        # 提取错误代码
        error_code_pattern = r'错误代码[：:]\s*([A-Z0-9_-]+)'
        error_codes = re.findall(error_code_pattern, text, re.IGNORECASE)
        structured_data['error_codes'] = error_codes
        
        # 提取IP地址
        ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
        ips = re.findall(ip_pattern, text)
        structured_data['ip_addresses'] = ips
        
        # 提取URL
        url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
        urls = re.findall(url_pattern, text)
        structured_data['urls'] = urls
        
        # 提取时间戳
        timestamp_pattern = r'\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}'
        timestamps = re.findall(timestamp_pattern, text)
        structured_data['timestamps'] = timestamps
        
        return structured_data
    
    def add_parsing_pattern(self, category: str, pattern: str) -> None:
        """
        添加解析模式
        
        Args:
            category: 分类名称
            pattern: 正则表达式模式
        """
        try:
            compiled_pattern = re.compile(pattern, re.IGNORECASE)
            
            if category not in self.compiled_patterns:
                self.compiled_patterns[category] = []
            
            self.compiled_patterns[category].append(compiled_pattern)
            logger.info(f"添加解析模式: {category} -> {pattern}")
            
        except Exception as e:
            logger.error(f"添加解析模式失败: {e}")
    
    def get_parsing_stats(self) -> Dict[str, Any]:
        """
        获取解析统计信息
        
        Returns:
            解析统计信息
        """
        stats = {}
        for category, patterns in self.compiled_patterns.items():
            stats[category] = len(patterns)
        
        return {
            'total_patterns': sum(len(patterns) for patterns in self.compiled_patterns.values()),
            'categories': list(self.compiled_patterns.keys()),
            'patterns_per_category': stats
        } 